package com.mall.shopping.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mall.shopping.IProductService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.converter.ContentConverter;
import com.mall.shopping.converter.ProductConverter;
import com.mall.shopping.dal.entitys.*;
import com.mall.shopping.dal.persistence.ItemDescMapper;
import com.mall.shopping.dal.persistence.ItemMapper;
import com.mall.shopping.dal.persistence.PanelContentMapper;
import com.mall.shopping.dal.persistence.PanelMapper;
import com.mall.shopping.dto.*;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Arrays;
import java.util.List;


/**
 * @Author: ZaiRiChangYe
 * @Date: 2020/5/13 10:32
 * @Description:
 */
@Service
@Component
public class ProductServiceImpl implements IProductService {

    @Autowired
    ItemMapper itemMapper;

    @Autowired
    ItemDescMapper descMapper;

    @Autowired
    ProductConverter productConverter;

    @Autowired
    PanelMapper panelMapper;

    @Autowired
    ContentConverter contentConverter;

    @Autowired
    PanelContentMapper contentMapper;
    /**
     * 查询商品详情
     * @param request
     * @return
     */
    @Override
    public ProductDetailResponse getProductDetail(ProductDetailRequest request) {
        ProductDetailResponse response = new ProductDetailResponse();

        Long id = request.getId();
        Example example = new Example(Item.class);
        example.createCriteria().andEqualTo("id",id);
        List<Item> items = itemMapper.selectByExample(example);
        Item item = items.get(0);
        ProductDetailDto productDetailDto = new ProductDetailDto();
        productDetailDto.setProductId(item.getId());
        productDetailDto.setProductName(item.getTitle());
        productDetailDto.setSalePrice(item.getPrice());
        productDetailDto.setSubTitle(item.getSellPoint());
        productDetailDto.setLimitNum(item.getLimitNum().longValue());

        // 判断一下
        if (CollectionUtils.isEmpty(items)){
            response.setCode(ShoppingRetCode.DB_EXCEPTION.getCode());
            response.setMsg(ShoppingRetCode.DB_EXCEPTION.getMessage());
        }
        // TODO 获取对应商品 -- 等待mapStruct恢復

        // set一下detail
        ItemDesc desc = descMapper.selectByPrimaryKey(id);
        String itemDesc = desc.getItemDesc();
        productDetailDto.setDetail(itemDesc);

        // set一下productImageSmall
        String image = item.getImage();
        String[] images = image.split(",");
        List<String> list = Arrays.asList(images);
        productDetailDto.setProductImageSmall(list);

        // set一下productImageBig
        String productImageBig = images[0];
        productDetailDto.setProductImageBig(productImageBig);

        // 最后封装进response，返回
        response.setProductDetailDto(productDetailDto);
        return response;
    }

    /**
     * 查询所有商品（分页）具体实现
     */
    @Override
    public AllProductResponse getAllProduct(AllProductRequest request) {

        // 牛一个response
        AllProductResponse response = new AllProductResponse();

        // 分页显示
        Integer page = request.getPage();
        Integer size = request.getSize();
        PageHelper.startPage(page,size);

        // 降序或者升序
        Example example = new Example(Item.class);
        String sort = request.getSort();
        if (!StringUtils.isEmpty(sort)){
            if ("1".equals(sort)){
                example.setOrderByClause("price" + "DESC");
            }
            if ("-1".equals(sort)){
                example.setOrderByClause("price" + "ASC");
            }
        }

        // 价格区间
        Integer priceGt = request.getPriceGt();
        Integer priceLte = request.getPriceLte();
        if (priceGt != null){
            example.createCriteria().andGreaterThanOrEqualTo("price",priceGt);
        }
        if (priceLte != null){
            example.createCriteria().andLessThanOrEqualTo("price",priceLte);
        }

        // 查詢一下下
        List<Item> items = itemMapper.selectByExample(example);
        // 轉換一下下
        List<ProductDto> productDtos = productConverter.items2Dto(items);

        // 顯示total
        PageInfo<ProductDto> info = new PageInfo<>(productDtos);
        long total = info.getTotal();

        // 組合response，并返回
        response.setProductDtoList(productDtos);
        response.setTotal(total);
        return response;
    }

    /**
     * 获取推荐的商品板块具体实现
     * @return
     */
    @Override
    public RecommendResponse getRecommendGoods() {
        // 牛一个response
        RecommendResponse response = new RecommendResponse();
        Example example1 = new Example(Panel.class);
        // 查询position为1的panels -- 商品推荐
        example1.createCriteria().andEqualTo("position",1);
        List<Panel> panels = panelMapper.selectByExample(example1);
        // 转换为panelDtos
        List<PanelDto> panelDtos = contentConverter.panels2Dto(panels);

        // 获取到该条panel
        PanelDto panelDto = panelDtos.get(0);
            Integer panelId = panelDto.getId();
            Example example2 = new Example(PanelContent.class);
            // 來查詢panelContent
            example2.createCriteria().andEqualTo("panelId",panelId);
            List<PanelContent> panelContents = contentMapper.selectByExample(example2);
            // 轉換一下
            List<PanelContentItemDto> itemDtos = contentConverter.panelContents2ItemDto(panelContents);
            for (PanelContentItemDto itemDto : itemDtos) {
                // 获取到productId取到item表中查询商品名称和卖点
                Long productId = itemDto.getProductId();
                Example example3 = new Example(Item.class);
                example3.createCriteria().andEqualTo("id",productId);
                List<Item> items = itemMapper.selectByExample(example3);
                // 塞入
                for (Item item : items) {
                    // 商品名称
                    itemDto.setProductName(item.getTitle());
                    // 卖点
                    itemDto.setSubTitle(item.getSellPoint());
                    // 价格
                    itemDto.setSalePrice(item.getPrice());
                }
            }
            panelDto.setPanelContentItems(itemDtos);
        response.setPanelContentItemDtos(panelDtos);
        return response;
    }
}
